package com.example.mywanandroid.ui.nav.mine.coinrank;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.mywanandroid.BR;
import com.example.mywanandroid.R;
import com.example.mywanandroid.base.BaseFragment;
import com.example.mywanandroid.bean.responsebean.CoinRankBean;
import com.example.mywanandroid.databinding.FragmentListBinding;
import com.example.mywanandroid.navinterface.ScrollToTop;
import com.example.mywanandroid.ui.adapter.CommonAdapter;

public class CoinRankListFragment extends BaseFragment<FragmentListBinding,CoinRankViewModel> implements ScrollToTop {

    private CommonAdapter<CoinRankBean.RankDataBean> commonAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_list;
    }

    @Override
    protected void initViewModel() {
        mViewModel = new ViewModelProvider(this).get(CoinRankViewModel.class);
    }

    @Override
    protected void bindViewModel() {

    }

    @Override
    protected void init() {
        mViewModel.loadData();
        initRecycler();
        initRefreshLayout();

        addObserver();
    }

    private void initRecycler() {
        mDataBinding.refreshLayout.setOnRefreshListener(refreshLayout -> mViewModel.refreshData(true));
        mDataBinding.refreshLayout.setOnLoadMoreListener(refreshLayout -> mViewModel.refreshData(false));
    }

    private void initRefreshLayout() {
        commonAdapter = new CommonAdapter<>(R.layout.item_coin_rank, com.example.mywanandroid.BR.coinRank);
        mDataBinding.recycle.setLayoutManager(new LinearLayoutManager(getContext()));
        mDataBinding.recycle.setAdapter(commonAdapter);
    }

    private void addObserver() {
        mViewModel.getCoinRankList().observe(this,coinRankBean -> {

            if (coinRankBean.getCurPage() >= coinRankBean.getPageCount()) {
                mDataBinding.refreshLayout.finishLoadMoreWithNoMoreData();
            }

            mDataBinding.refreshLayout.finishRefresh();
            mDataBinding.refreshLayout.finishLoadMore();

            commonAdapter.onItemDatasChanged(coinRankBean.getDatas());
        });
    }

    @Override
    protected boolean isSupportLoad() {
        return true;
    }

    @Override
    public void scrollToTop() {
        mDataBinding.recycle.smoothScrollToPosition(0);
    }
}
